package com.camemax.rabbitmq.utils;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.nio.charset.StandardCharsets;
// *********************
// ** @Date: 2021-06-09
// ** @Author: Camemax
// ** @Description: Fix the Consumer Template Bug: constructor only can setting one arguments[queueName]. (now could be two for work mode testing.)
// *********************
public class ConsumersModulesRunnable implements Consumers,Runnable {
    private ConnectionFactory factory = RabbitMQUtils.createFactory();
    private Connection connection = null;
    private Channel channel = null;
    private String queueName;
    private Boolean autoArk; // Default FALSE.

    public ConsumersModulesRunnable(String queueName){
        this(queueName, Boolean.FALSE);
    }

    public ConsumersModulesRunnable(String queueName, Boolean autoArk){
        this.queueName = queueName;
        this.autoArk = autoArk;
    }

    @Override
    public void run() {
        try {
            String consumerName = Thread.currentThread().getName(); // Use thread's name as RabbitMQ Consumers' name.
            connection = factory.newConnection();
            channel = connection.createChannel();
            channel.basicConsume(
                    queueName,
                    autoArk,
                    (consumer, message) -> System.out.println(consumerName + " accepts message: " + new String(message.getBody(), StandardCharsets.UTF_8)),
                    (consumer) -> System.out.println(consumerName + " accepts failed!")
            );

            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            RabbitMQUtils.close(channel, connection);
        }
    }
}
